package com.yyh.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yyh.config.JwtConfig;
import com.yyh.entity.Users;
import com.yyh.service.IUsersService;


@RestController
public class LoginController {
	 @Resource
	    private JwtConfig jwtConfig ;
	 @Autowired
	 IUsersService userService;
	    /*
	     * 返参格式
	     * {
	     *     "userName": "ID123",
	     *     "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMSIsImlhdCI6MTU4ODg2MDE0MCwiZXhwIjoxNTg4ODYzNzQwfQ.pwpuI-E2xskyqqzjeWe_DU-ASIyyrwbKswX2da_GC9e2ucZ0xfGSbXdmHQWIZ5ITJXrZLgTtWNBg_ceDivkqtA"
	     * }
	     */
	    // 拦截器直接放行，返回Token
	 @PostMapping("/login")
	    public Map<String,Object> login (@RequestParam("loginName") String loginName,
	                                     @RequestParam("password") String password){
	        Map<String,Object> result = new HashMap<>() ;
	        
	        //数据源校验
	        QueryWrapper<Users> queryWrapper = new QueryWrapper<Users>();
	        queryWrapper.eq("login_name",loginName).eq("password",password);
	        Users one = userService.getOne(queryWrapper, false);
	        if(one == null) {
	        	result.put("code", 501);
	        	result.put("msg", "登录失败");
	        }else {
	        	String token = jwtConfig.getToken(loginName+password) ;
	        	if(!StringUtils.isEmpty(token)) {
	        		result.put("token", token);
	        	}
	        	result.put("code", 0);
	        	result.put("data", one);
	        }
	        return result ;
	    }
}